import { View, Text, Button, Checkbox } from "@tarojs/components";
import { useLoad } from "@tarojs/taro";
import "./index.scss";
import { useDispatch, useSelector } from "react-redux";
import ListItem from "../../components/list-item";
import { AtInputNumber } from "taro-ui";
import { changeCartList, changeState, deleteCartList } from "../../store/cart";
import NumberStep from "../../components/number-step";

export default function Cart() {
  const cartList = useSelector((state) => state.cart.cartList);
  const totalPrice = cartList
    .filter((v) => v.state)
    .reduce((p, n) => {
      return p + n.count * n.price;
    }, 0);
  const allState = cartList.every((v) => v.state);
  const dispatch = useDispatch();
  const handleChange = (value, id) => {
    dispatch(
      changeCartList({
        id: id,
        count: value,
      })
    );
  };
  useLoad(() => {
    console.log("Page loaded.");
  });

  return (
    <View className="cart">
      <View>
        {cartList.map((v, i) => {
          return (
            <ListItem
              key={i}
              v={v}
              desc={
                <View>
                  <NumberStep
                    count={v.count}
                    onChange={(value) => handleChange(value, v.id)}
                    min={1}
                  ></NumberStep>
                  <Button type="warn" size="mini" onClick={() => dispatch(deleteCartList(v))}>删除</Button>
                </View>
              }
              preFix={
                <Checkbox
                  checked={v.state}
                  onClick={() => dispatch(changeState(v))}
                ></Checkbox>
              }
            ></ListItem>
          );
        })}
      </View>
      <View>
        <Checkbox checked={allState} onClick={() => {}}>
          全选
        </Checkbox>
        总价钱：{totalPrice}
      </View>
    </View>
  );
}
